package com.tulele.vtool.task.async;

import com.tulele.vtool.bus.mapper.UserPunchClockInfoMapper;
import com.tulele.vtool.bus.mapper.log.PushDetailLogMapper;
import com.tulele.vtool.bus.model.PunchClockArticleInfo;
import com.tulele.vtool.bus.model.UserInfo;
import com.tulele.vtool.bus.model.log.PushDetailLog;
import com.tulele.vtool.bus.service.IUserPunchClockInfoService;
import com.tulele.vtool.bus.service.SysGzhService;
import com.tulele.vtool.model.PlatformSysInfo;
import com.tulele.vtool.util.DateUtil;
import com.tulele.vtool.util.RedisCacheUtil;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;

@Component
@Slf4j
public class UploadTempMsgPushAsync430Task {


    @Autowired
    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private IUserPunchClockInfoService userPunchClockInfoService;

    @Autowired
    private UserPunchClockInfoMapper userPunchClockInfoMapper;

    @Autowired
    private PushDetailLogMapper pushDetailLogMapper;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Async("taskExecutor2")
    public void execute(UserInfo user, String profile, Integer headId) {

        PunchClockArticleInfo punchClockArticleInfo = userPunchClockInfoService.getUserPunchClockArticleInfo();

        pubExecute(user, profile, headId, punchClockArticleInfo);
    }

    private void pubExecute(UserInfo user, String profile, Integer headId, PunchClockArticleInfo articleInfo){
        Integer ret = 2;

        if (articleInfo != null) {

            String clockTimeStr = DateUtil.getFormatDate("yyyy-MM-dd", DateUtil.getCurDate());
            int clockStatus = Optional.ofNullable(userPunchClockInfoMapper.queryUserSpecialDayPunchClockStatus(user.getUserId(), clockTimeStr)).orElse(0);
            int clockDays = userPunchClockInfoService.getUserClockDays(user.getUserId());

            if (clockStatus == 0) { //20200229 hyl，用户当天没打 才加1
                clockDays = clockDays + 1;
            }

            PlatformSysInfo sysGzh = sysGzhService.getPlatformSysInfo(profile);
            // 发送模板消息接口
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    // 接收者openid
                    .toUser(user.getOpenId())
                    // 模板id
                    .templateId(sysGzh.getSysGzh().getGroundingTempId())
                    // 模板跳转链接
                    .url(sysGzh.getFrontDomain() + "index.html" )
                    .build();

            String firstMsg = "☀早上好！今天的早安问候送达，一起来打卡！";

            // 添加模板数据
            templateMessage.addData(new WxMpTemplateData("first", firstMsg, "#FF00FF"))
                    .addData(new WxMpTemplateData("keyword1", "早安打卡", "#FF00FF"))
                    .addData(new WxMpTemplateData("keyword2", "早安第 " + clockDays + " 天: " +articleInfo.getClockArticleTitle()+ "\n", "#FF00FF"))
                    .addData(new WxMpTemplateData("remark", "🔴下方回复数字【  7  】领取今日早安打卡！", "#FF0000"));

            PushDetailLog pushDetailLog = new PushDetailLog();
            pushDetailLog.setGzhCode(profile);
            pushDetailLog.setUserId(user.getUserId());
            pushDetailLog.setMsgType(14);//日报
            pushDetailLog.setPushTime(new Date());
            pushDetailLog.setHeadId(headId);
            pushDetailLog.setOpenId(user.getOpenId());
            try {
                WeixinServiceDL weixinService = WeixinServiceMap.getWeixinService(profile);
                if (weixinService == null) {
                    weixinService = objectFactory.getObject();
                    weixinService.reSetConfigStorage(profile);
                    WeixinServiceMap.putWeixinService(profile, weixinService);
                }
                weixinService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                ret = 0;
                pushDetailLog.setMsg("成功");
            } catch (WxErrorException e) {
                ret = 2;
                pushDetailLog.setMsg(e.getMessage());
            }
            pushDetailLog.setResult(ret);

            if(ret.equals(0)) {
                redisCacheUtil.setCacheObject("UPLOAD_TEMP_MSG_PUSH" + user.getUserId(), 1, 3600*24);//作用：记录发了多少模板消息给这个用户
            }

            pushDetailLogMapper.addPushDetailLog(pushDetailLog);
        }
    }
}
